package com.opennews.openplatform.familyexpenseapi.service

import com.opennews.openplatform.familyexpenseapi.config.AppConfigProperties
import com.opennews.openplatform.familyexpenseapi.entity.Tables.BANK
import com.opennews.openplatform.familyexpenseapi.entity.tables.records.BankRecord
import com.opennews.openplatform.familyexpenseapi.jooq.DSLContextWrapper
import org.jooq.DSLContext
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.core.env.Environment
import org.springframework.stereotype.Service

@Service
class BankService(
    private val appConfigProperties: AppConfigProperties,
    private val dslContext: DSLContext,
    private val dslContextWrapper: DSLContextWrapper,
    private val env: Environment,
) {
    /**
     * Prepares the initial data for Bank and BankCard.
     */
    fun init() {
        if (!dslContextWrapper.exists(BANK)) {
            mutableListOf<BankRecord>().run {
                add(createRecord("上海银行", "BOSC"))
                add(createRecord("建行", "CCB"))
                add(createRecord("交行", "BCM"))
                add(createRecord("招行", "CMB"))
                dslContext.batchInsert(this)
            }
        }
    }

    /**
     * Gets bank logo url based on its short name.
     *
     * @param shortName: The bank short name.
     * @return The full url of the bank logo.
     */
    fun getLogoUrl(shortName: String?): String? {
        return if (!shortName.isNullOrBlank()) {
            String.format(
                "%s%s/%s.png",
                appConfigProperties.resource.httpBaseUrl,
                appConfigProperties.resource.bankLogoUrl,
                shortName.lowercase()
            )
        } else {
            null
        }
    }

    /**
     * Queries all banks with basic info.
     *
     * @return List of map instance which contains keys below.
     * id: String of bank id.
     * name: String of bank name.
     * shortName: String of bank short name.
     */
    fun queryAllWithBasicInfo(): List<Map<String, Any>> {
        return dslContext.select(
            BANK.ID.`as`("id"),
            BANK.NAME.`as`("name"),
            BANK.SHORT_NAME.`as`("shortName")
        ).from(BANK)
            .fetch()
            .map { p ->
                val item = p.intoMap()
                item["logoUrl"] = getLogoUrl(item["shortName"] as String?)

                item
            }
    }

    /**
     * Creates a BankRecord with the provided name and shortName.
     */
    private fun createRecord(name: String, shortName: String): BankRecord {
        val record = dslContext.newRecord(BANK)
        record.name = name
        record.shortName = shortName

        return record
    }
}